//
//  LogManager.m
//  Manager
//
//  Created by issac on 15/9/2.
//  Copyright (c) 2015年 52xiaoluo. All rights reserved.
//

#import "LogManager.h"

enum {
    NODATA = 0,
    HASDATA = 1
};

@implementation LogManager
{
    NSMutableArray *logItems;
    NSConditionLock *lock;
    NSString *logDir;
    NSFileHandle *logHandle;
    NSString *title;
    NSDateFormatter *dateFormater;
    NSDate *nextDate;
}

static LogManager* _instance = nil;


+(instancetype) shareInstance
{
    static dispatch_once_t onceToken ;
    dispatch_once(&onceToken, ^{
        _instance = [[LogManager alloc] init] ;
    });
    
    return _instance ;
}

-(id)init {
    self = [super init];
    if (self) {
        dateFormater = [[NSDateFormatter alloc] init];
        [dateFormater setDateFormat:@"yy_MM_dd_HH"];
        title = [NSString stringWithFormat:@"device=%@ iosName=%@ version=%f",DeviceName,IOSName,IOSVersion];
        logItems = [[NSMutableArray alloc] init];
        lock = [[NSConditionLock alloc] initWithCondition:0];
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
        NSString *cacheDirectory = [paths objectAtIndex:0];
        logDir = [cacheDirectory stringByAppendingString:@"/log/"];
        NSFileManager *fileManager = [NSFileManager defaultManager];
        if(![fileManager fileExistsAtPath:logDir])
        {
            [fileManager createDirectoryAtPath:logDir withIntermediateDirectories:YES attributes:nil error:nil];
        }
        [self initLogFile];
        [NSThread detachNewThreadSelector:@selector(writeLog) toTarget:self withObject:nil];
    }
    return self;
}


-(void)initLogFile {
    if (logHandle) {
        [logHandle closeFile];
        logHandle = nil;
    }
    NSDate *currentDate = [NSDate date];
    NSString *timeStr = [dateFormater stringFromDate:currentDate];
    NSString *fileName = [NSString stringWithFormat:@"%@.txt",timeStr];
    NSString *logFile = [logDir stringByAppendingString:fileName];
    NSLog(@"initLogFile=%@",logFile);
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if(![fileManager fileExistsAtPath:logFile])
    {
        [title writeToFile:logFile atomically:true encoding:NSUTF8StringEncoding error:nil];
    }
    logHandle = [NSFileHandle fileHandleForWritingAtPath:logFile];
    [logHandle seekToEndOfFile];
    
    NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSDateComponents *offsetComponents = [[NSDateComponents alloc] init];
    [offsetComponents setHour:1];
    nextDate = [gregorian dateByAddingComponents:offsetComponents toDate: currentDate options:0];
    unsigned unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit |  NSDayCalendarUnit | NSHourCalendarUnit;
    NSDateComponents *comps = [gregorian components:unitFlags fromDate:nextDate];
    nextDate = [gregorian dateFromComponents:comps];
}


-(void) log:(NSString *)fmt,... {
    va_list args;
    va_start(args,fmt);
    NSString *msg=[[NSString alloc] initWithFormat:fmt arguments:args];
    va_end(args);
    NSLog(@"%@",msg);
    [lock lock];
    [logItems addObject:msg];
    [lock unlockWithCondition:HASDATA];
}

-(void)writeLog {
    while (true) {
        [lock lockWhenCondition:HASDATA];
        NSString *msg = logItems[0];
        [logItems removeObjectAtIndex:0];
        [lock unlockWithCondition:logItems.count > 0 ? HASDATA : NODATA];
        if ([[NSDate date]compare:nextDate] > 0) {
            [self initLogFile];
        }
        [logHandle writeData:[msg dataUsingEncoding:NSUTF8StringEncoding]];
    }
}

- (void)uploadWithStart:(NSDate *)start andEnd:(NSDate *)end
{
    NSString *startStr = [dateFormater stringFromDate:start];
    NSString *endStr = [dateFormater stringFromDate:end];
    
    
    
    
    
}


@end
